package com.bootdo.fx.domain;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.AuthUtil;
import com.bootdo.common.utils.IdWorker;
import com.bootdo.fx.service.UserInfoService;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WXController {


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private IdWorker idWorker;


    @RequestMapping("/weixinAutoLogin")
    public void weixinAutoLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String backUrl="http://3261045722cwy.vicp.io/wx/callBack";
        /**
         *这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
         **/
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID+
                "&redirect_uri=" + URLEncoder.encode(backUrl,"UTF-8")+
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        response.sendRedirect(url);
    }

    @RequestMapping("/weixinComeback")
    public void weixinComeback(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String code=request.getParameter("code");
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID+
                "&secret=" +AuthUtil.APPSECRET+
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        String openid=jsonObject.getString("openid");
        String token=jsonObject.getString("access_token");
        String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=" +token+
                "&openid=" +openid+
                "&lang=zh_CN";
        JSONObject userInfo=AuthUtil.doGetJson(infoUrl);
        System.out.println(userInfo);

        UserInfoDO ui = new UserInfoDO();
        ui.setUserId(idWorker.nextId());
        ui.setUserAvatar(String.valueOf(userInfo.get("headimgurl")));

        //用户的上级分销用户ID
        String upUserId = request.getParameter("state");
        ui.setUpUserId(Long.parseLong(upUserId));
        ui.setUserCity(String.valueOf(userInfo.get("用户所在城市")));
        ui.setUserCountry(String.valueOf(userInfo.get("country")));
        ui.setUserCreateTime(new Date());
        ui.setUserIsDistributor(0);
        ui.setUserNickname(String.valueOf(userInfo.get("nickname")));
        ui.setUserOpenid(openid);
        ui.setUserSex(Integer.parseInt(String.valueOf(userInfo.get("sex"))));
        ui.setUserProvince(String.valueOf(userInfo.get("province")));

        Map<String,Object> map = new HashMap<>();
        map.put("userOpenid",openid);
        UserInfoDO userInfo1 = (UserInfoDO) userInfoService.list(map);
        int b = 0;
        if(userInfo1 == null){
            b = userInfoService.save(ui);
        }else {
            ui = userInfo1;
        }

        if(b > 0) {
            //用户信息存放到session里面
            request.getSession().setAttribute("userInfo", ui);

        }else{
            //登录失败，需要重新加载登录界面

        }

    }

    @RequestMapping("/indexPage")
    public String indexPage(){
        return "index";
    }
}
